package module;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;


/**
 * Servlet implementation class InitServlet
 */
public class InitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	public void init() throws ServletException {
		Connection con;
		ServletContext context = getServletContext();
		//On indique le nombre de resultats autorise par page
		context.setAttribute("nbresults", 10);
		
		//On calcule les types de produit les plus rependu pour les afficher dans le header
		try{
			Context namingContext = new InitialContext();
			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
			con = dataSource.getConnection();
			
			PreparedStatement pstmt=con.prepareStatement("SELECT COUNT(p.id_produit), tp.id_type, tp.nom FROM `type_produit` tp LEFT JOIN `produit` p ON p.id_type=tp.id_type GROUP BY tp.id_type ORDER BY COUNT(p.id_produit) DESC, tp.nom");
			ResultSet rs = pstmt.executeQuery();
			
			Map<Integer, String> listMenu = new LinkedHashMap<Integer, String>();
			
			while(rs.next()) {
				listMenu.put(rs.getInt("id_type"), rs.getString("nom"));
			}
			context.setAttribute("menu", listMenu);
			
			pstmt = con.prepareStatement("SHOW COLUMNS FROM `annonce` WHERE Field = 'etat'");
			rs = pstmt.executeQuery();
			String etat;
			
			Map<Integer, String> etats = new LinkedHashMap<Integer, String>();
			int cpt = 0;
			
			if(rs.next()){
				etat = rs.getString("Type");
				String[] buff = etat.split(",");
				for(String s : buff) {
					etats.put(cpt++, s.substring(s.indexOf('\'') + 1, s.lastIndexOf('\'')));
				}
			}
			context.setAttribute("etats", etats);
		}catch(Exception e){}
	}
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InitServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
